import { sensitiveWordsConfig } from '@renderer/config/sensitiveWords'
import { DfaFilter } from '@renderer/core/filters/dfaFilter'

/**
 * 敏感词过滤服务
 * 用于对大模型回复内容进行敏感词过滤
 */
class FilterService {
  private filter: DfaFilter | null = null
  private useRegex: boolean = false
  private useFuzzy: boolean = false

  constructor() {
    this.initFilter()
  }

  /**
   * 初始化敏感词过滤器
   */
  private initFilter() {
    // 合并用户自定义敏感词和系统内置敏感词
    const allSensitiveWords = [...new Set([...sensitiveWordsConfig.words, ...sensitiveWordsConfig.systemWords])]
    if (sensitiveWordsConfig.enabled && allSensitiveWords.length > 0) {
      this.filter = new DfaFilter(allSensitiveWords, this.useRegex, this.useFuzzy)
    } else {
      this.filter = null
    }
  }

  /**
   * 更新敏感词列表
   * @param words 敏感词列表
   * @returns 是否更新成功
   */
  public updateSensitiveWords(words: string[]): boolean {
    // 检查是否允许用户配置敏感词
    if (!sensitiveWordsConfig.allowUserConfig) {
      console.warn('[FilterService] User configuration of sensitive words is disabled by system settings')
      return false
    }

    sensitiveWordsConfig.words = words
    this.initFilter()
    return true
  }

  /**
   * 启用或禁用敏感词过滤
   * @param enabled 是否启用
   * @returns 是否设置成功
   */
  public setEnabled(enabled: boolean): boolean {
    // 检查是否允许用户配置敏感词过滤
    if (!sensitiveWordsConfig.allowUserConfig) {
      console.warn('[FilterService] User configuration of sensitive word filtering is disabled by system settings')
      return false
    }

    sensitiveWordsConfig.enabled = enabled
    this.initFilter()
    return true
  }

  /**
   * 设置正则优化和模糊匹配开关
   */
  public setOptions({ useRegex, useFuzzy }: { useRegex?: boolean; useFuzzy?: boolean }) {
    if (typeof useRegex === 'boolean') this.useRegex = useRegex
    if (typeof useFuzzy === 'boolean') this.useFuzzy = useFuzzy
    this.initFilter()
  }

  /**
   * 过滤文本中的敏感词
   * @param text 需要过滤的文本
   * @returns 过滤后的文本
   */
  public filterText(text: string): string {
    if (!this.filter || !sensitiveWordsConfig.enabled) {
      return text
    }
    return this.filter.replace(text)
  }

  /**
   * 检测文本中是否包含敏感词
   * @param text 需要检测的文本
   * @returns 检测到的敏感词列表
   */
  public detectSensitiveWords(text: string): string[] {
    if (!this.filter || !sensitiveWordsConfig.enabled) {
      return []
    }
    return this.filter.detect(text)
  }
}

// 导出单例实例
export default new FilterService()
